"""
Response Formatter
==================

Standardized API response formatting utilities.
Provides consistent response structure across all API endpoints.
"""

from flask import jsonify
from typing import Any, Dict, Optional, Union
import datetime

class ResponseFormatter:
    """
    Standardized response formatter for API responses.
    
    Provides consistent structure:
    {
        "status": "success|error",
        "message": "descriptive message",
        "timestamp": "ISO8601 timestamp",
        "data": {...},  // success data
        "error_code": "error_code",  // error only
        "errors": {...}  // validation errors only
    }
    """
    
    @staticmethod
    def format_success(
        message: str = "Success",
        data: Optional[Dict[str, Any]] = None,
        metadata: Optional[Dict[str, Any]] = None
    ) -> Dict[str, Any]:
        """
        Format success response.
        
        Args:
            message: Success message
            data: Response data
            metadata: Additional metadata
        
        Returns:
            Formatted response dictionary
        """
        response = {
            "status": "success",
            "message": message,
            "timestamp": datetime.datetime.utcnow().isoformat()
        }
        
        if data is not None:
            response["data"] = data
        
        if metadata is not None:
            response["metadata"] = metadata
        
        return response
    
    @staticmethod
    def format_error(
        message: str = "Error",
        error_code: Optional[str] = None,
        errors: Optional[Dict[str, Any]] = None,
        status_code: Optional[int] = None
    ) -> Dict[str, Any]:
        """
        Format error response.
        
        Args:
            message: Error message
            error_code: Machine-readable error code
            errors: Detailed error information
            status_code: HTTP status code
        
        Returns:
            Formatted response dictionary
        """
        response = {
            "status": "error",
            "message": message,
            "timestamp": datetime.datetime.utcnow().isoformat()
        }
        
        if error_code:
            response["error_code"] = error_code
        
        if errors is not None:
            response["errors"] = errors
        
        if status_code:
            response["status_code"] = status_code
        
        return response
    
    @staticmethod
    def format_paginated_response(
        data: list,
        page: int,
        per_page: int,
        total: int,
        message: str = "Success"
    ) -> Dict[str, Any]:
        """
        Format paginated response.
        
        Args:
            data: List of items
            page: Current page number
            per_page: Items per page
            total: Total number of items
            message: Success message
        
        Returns:
            Formatted paginated response
        """
        total_pages = (total + per_page - 1) // per_page
        
        return {
            "status": "success",
            "message": message,
            "timestamp": datetime.datetime.utcnow().isoformat(),
            "data": data,
            "pagination": {
                "page": page,
                "per_page": per_page,
                "total": total,
                "total_pages": total_pages,
                "has_next": page < total_pages,
                "has_prev": page > 1
            }
        }

# Global response formatter instance
response_formatter = ResponseFormatter()

def format_response(
    status: str = "success",
    message: str = "",
    data: Optional[Dict[str, Any]] = None,
    error_code: Optional[str] = None,
    errors: Optional[Dict[str, Any]] = None,
    status_code: Optional[int] = None,
    metadata: Optional[Dict[str, Any]] = None
) -> tuple:
    """
    Convenience function to format and return API response.
    
    Args:
        status: Response status ("success" or "error")
        message: Response message
        data: Response data (for success)
        error_code: Error code (for error)
        errors: Detailed errors (for validation errors)
        status_code: HTTP status code
        metadata: Additional metadata
    
    Returns:
        Tuple of (response_dict, status_code)
    """
    if status == "success":
        response = response_formatter.format_success(
            message=message or "Success",
            data=data,
            metadata=metadata
        )
    else:
        response = response_formatter.format_error(
            message=message or "Error",
            error_code=error_code,
            errors=errors
        )
    
    # Default status codes
    if status_code is None:
        if status == "success":
            status_code = 200
        else:
            status_code = 400
    
    return jsonify(response), status_code